package com.sftz.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import org.nutz.lang.Encoding;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.aliyuncs.vod.model.v20170321.GetMezzanineInfoResponse.Mezzanine;
import com.sftz.framework.service.aliyun.AliyunVodUtil;
import com.uxuexi.core.common.exception.impl.BusinessException;
import com.uxuexi.core.common.util.Util;

/**
 * 文件下载工具类
 *
 * @author   朱晓川
 * @Date	 2017年11月21日
 */
public final class DownloadUtil {

	private static final Log log = Logs.get();

	/**
	 * 从url地址下载文件,返回InputStream
	 */
	public static InputStream download(String downloadUrl) {
		OkHttpClient client = new OkHttpClient();
		Request req = new Request.Builder().url(downloadUrl).build();
		Response resp = null;
		try {
			resp = client.newCall(req).execute();
			if (resp.isSuccessful()) {
				ResponseBody body = resp.body();
				InputStream is = body.byteStream();
				return is;
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Unexpected code " + resp);
		}
		return null;
	}

	public static InputStream downloadAlivod(final HttpServletResponse response, String vid) {
		try {
			if (Util.isEmpty(vid)) {
				throw new IllegalArgumentException("视频ID不能为空");
			}

			Mezzanine mezzanine = AliyunVodUtil.getMezzanine(vid);
			String fname = mezzanine.getFileName();

			String filename = URLEncoder.encode(fname, Encoding.UTF8);
			response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

			String fileUrl = mezzanine.getFileURL();
			InputStream is = DownloadUtil.download(fileUrl);
			return is;
		} catch (Exception e) {
			throw new BusinessException("下载失败！");
		}
	}

}